package com.my.commonlibrary.net.netroid;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by qinghua on 2015/6/19.
 */
public class Urls {

    //测试接口。
    public static final String BASE_URL_DEBUG = "http://test.new.escqz.cyhz.com";
    //正式接口。
    public static final String BASE_URL_RELATION = "http://new.escqz.cyhz.com";
    //实际请求的url.
    public static String BASE_URL = BASE_URL_DEBUG;

    // 用户信息
    public static String RUL_USER_INFO = "/mars/user/v1/detail";

    private static HashMap<String, Object> baseMap;

    /**
     * @param path   访问路径
     * @param parmas 访问参数
     * @return url
     */
    public static String getUrl(String path, Map<String, Object> parmas) {
        getBaseParams();
        if (null == parmas || parmas.size() == 0) {
            return getUrlWithoutBaseInfo(path, baseMap);
        }

        parmas.putAll(baseMap);
        return getUrlWithoutBaseInfo(path, parmas);
    }

    public static String getUrl(String path) {
        return getUrl(path, null);
    }

    /**
     * 不待userId 和 token的请求
     *
     * @param path
     * @param parmas
     * @return
     */
    public static String getUrlWithoutBaseInfo(String path, Map<String, Object> parmas) {
        return BASE_URL + path + "?" + getUrlParamsByMap(parmas);
    }


    private static void getBaseParams() {
        baseMap = new HashMap<String, Object>();
//        SharedPreferences sp = CarSourceApplication.getApplication().getShare();
//        String userId = sp.getString("user_id", "");
//        String authCode = sp.getString("auth_code", "");
        String userId = "576796";
        String authCode = "CB53A41C2C403A19C14DA32609FA2C7F";
        if (!userId.equals("") && !authCode.equals("")) {
            baseMap.put("user_id", userId);
            baseMap.put("auth_code", authCode);
        }
    }

    /**
     * 将map转换成url
     *
     * @param map
     * @return
     */
    public static String getUrlParamsByMap(Map<String, Object> map) {
        if (map == null) {
            return "";
        }
        StringBuffer sb = new StringBuffer();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            sb.append(entry.getKey() + "=" + entry.getValue());
            sb.append("&");
        }
        String s = sb.toString();
        if (s.endsWith("&")) {
            s = s.substring(0, s.length() - 1);
        }
        return s;
    }

}
